import base64
import logging
import random
import string
from datetime import timedelta

from django.core.cache import cache
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.core.signing import Signer
from django.http import JsonResponse
from django.shortcuts import render
from rest_framework.decorators import api_view
from rest_framework.parsers import JSONParser

from lianxi.models import userInfo, playrecord


# Create your views here.

#生成token1
def createtoken(username):
    #产生一个8为的随机字符串
    randomstr=''.join(random.choices(string.ascii_letters,k=8))
    #对字符串进行签名
    token=Signer().sign(randomstr+username)
    #把token保存到缓存中
    cache.set(f'test_{username}',token,timeout=timedelta(minutes=100).total_seconds())
    #把token值返回
    return  token

#生成token方法2
def token(username):
    randomstr=''.join(random.choices(string.ascii_letters,k=8))
    token=Signer.sign(randomstr+username)
    cache.set(f'test_{username}',token,timeout=timedelta(minutes=100).total_seconds())
#鉴权的方法
def checktoken(request):
    #获取前端传过来的token
    reqtoken=request.META.get('HTTP_TOKEN')
    #如果前端没有传token,返回False
    if reqtoken is None:
        return False,"XX"
    #先做一个反签名
    untoken=Signer().unsign(reqtoken)
    name=untoken[8:]
    #校验缓存中token,还存不存在
    cachetoken=cache.get(f"test_{name}")
    #判断缓存中的token是否有效
    if cachetoken is None:
        return  False,'xx'
    return  True,name

#判空的方法
def is_empty(c):
    return c is None or str(c).strip()==''

@api_view(['post'])
def login(request):
    data=request.data
    username=data['username']
    password=data['password']
    if is_empty(username) or is_empty(password):
        return JsonResponse({"messsage":"用户名或密码不能为空","code":404})
    if userInfo.objects.filter(username=username).exists()is False:
        return JsonResponse({"messsage": "用户名不存在", "code": 400})
    obj=userInfo.objects.get(username=username)
    if obj.password!=password:
        return JsonResponse({"messsage": "密码错误", "code": 400})


    #加密用户名
    bname=bytes(username,encoding='utf-8')
    b64name=base64.b64encode(bname).decode('utf-8')

    token=createtoken(b64name)
    return JsonResponse({"message":"登录成功",'token':token,'code':200})

@api_view(['get'])
def select(request):

    flag,name=checktoken(request)
    if flag is False:
        return JsonResponse({"message":"未登录请先登录","code":401})


    page=request.GET.get('page')
    pagesize=request.GET.get('pagesize')
    # 查询出所有数据对象
    allobj = playrecord.objects.filter()

    # 分页
    pageobj = Paginator(allobj, pagesize)

    try:
        singlepageobj = pageobj.page(page)
    except EmptyPage:
        # 数量
        singlepageobj = pageobj.page(pageobj.num_pages)
    except PageNotAnInteger:
        singlepageobj = pageobj.page(1)

    #顶一个空列表用于存数
    lis=[]
    for obj in singlepageobj.object_list:
        lis.append({
            'id':obj.id,
            'title':obj.track_id.title,
            'username':obj.user_id.username,
            'play_times':obj.play_time,
            'play_date':obj.play_date
        })
    return JsonResponse({"code":200,"data":lis,"items":allobj.count()})

@api_view(['post'])
def play(request):
    
    flag, name = checktoken(request)
    if flag is False:
        return JsonResponse({"message": "未登录请先登录", "code": 401})

    data=request.data
    user_id=data['user_id']
    track_id=data['track_id']

    if is_empty(user_id) or is_empty(track_id):
        return JsonResponse({"message":"参数不能为空","code":409})

    playrecord(track_id_id=track_id,user_id_id=user_id)
    return  JsonResponse({"message":"正在播放","code":200})